package com.socialrss.viewlisteners;
/*
* author : Sefa Sahin Koc
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;


import com.socialrss.R;
import com.socialrss.accounts.AbstractHolder;
import com.socialrss.accounts.FollowedPerson;
import com.socialrss.accounts.Group;
import com.socialrss.accounts.dbinterfaces.ConnectionTable;
import com.socialrss.adapters.SelectTypeClickListener;
import com.socialrss.adapters.StringWithStatus;
import com.socialrss.adapters.SwipeDetector;
import com.socialrss.constants.SocialNetworkNames;
import com.socialrss.utils.SocialRssModel;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Button;
import android.text.TextWatcher;
import android.text.Editable;

public class AddMoreConnections extends BaseActivity implements AbstractManageListListener{
	
	private ListView mainListView ;  
	private ArrayAdapter<AbstractHolder> listAdapter;
	private TextView searchConnTextView;
	private Button commitButton, selectConnTypeButton;
	private ArrayList<AbstractHolder>  connlist;
	private ArrayList<AbstractHolder> listNotOnView;
	private Group thiscat;
	private int[] idsOfParents;
	private LinkedHashMap<Integer, Boolean> selectedHolders;
	private LinkedHashMap<String, ArrayList<AbstractHolder>> allHolders;
	private ArrayList<StringWithStatus> conntype;
	private SelectTypeClickListener socialNetworkSelectListener;
	private SwipeDetector swipelistener;
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Generate list View from ArrayList 
		Bundle b = getIntent().getExtras();
		idsOfParents = b.getIntArray("idsOfParents");
		int thiscatid = b.getInt("categoryid");
		thiscat = (Group)SocialRssModel.Instance(this).getAbstractHolder(thiscatid, null, true);
		setContentView(R.layout.add_more_connections);
		
		//set group name label text
		TextView tempTextV = (TextView)findViewById(R.id.amc_groupNameLabel);
		tempTextV.setText(thiscat.getName());
	    //now initialize a hash map to categorize all holders depending on their social network
	    allHolders = new LinkedHashMap<String, ArrayList<AbstractHolder>>(5);
		
	    //initialize list options
	    conntype = new ArrayList<StringWithStatus>(5);
	    conntype.add(new StringWithStatus(SocialNetworkNames.FACEBOOK, true));
	    conntype.add(new StringWithStatus(SocialNetworkNames.TWITTER, true));
	    conntype.add(new StringWithStatus(SocialNetworkNames.GOOGLE, true));
	    conntype.add(new StringWithStatus(SocialNetworkNames.INSTAGRAM, true));
	    conntype.add(new StringWithStatus(SocialNetworkNames.CATEGORY, true));;
	    
	    //Initialize properties   
	    mainListView = (ListView) findViewById( R.id.connectionlist );  
	    
	    //Configure connlist for CustomAdapter
	    this.configureConnListForAdapter();
	    
	    //configure checkbox property for onclicklistener of listview
	    
	    // Create CustomAdapter for mainListView  
	    listAdapter = new CustomAdapter(this,R.layout.connlist, connlist);
	    mainListView.setAdapter( listAdapter );
	    mainListView.setClickable(false);
	    
	    //add listeners
	    addSwipeListenerToListView();
		addListenerOnSearchConnTextView();
		addListenerToFinishButton();
		addListenerToSelectConnTypeButton();
	}
	public void addSwipeListenerToListView(){
		//swipelistener = new SwipeDetector();
	    //mainListView.setOnTouchListener(swipelistener);
		mainListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				if(swipelistener.swipeDetected()){
					AbstractHolder temp = (AbstractHolder)mainListView.getItemAtPosition(arg2);
					if(temp.isGroup()){
						Intent i = new Intent(AddMoreConnections.this, AddMoreConnections.class);
						Bundle b = new Bundle();
						int[] parentIds = new int[idsOfParents.length +1];
						for (int j = 0; j < idsOfParents.length; j++) {
							parentIds[j] = idsOfParents[j];
						}
						parentIds[idsOfParents.length] = thiscat.getId();
						b.putIntArray("idsOfParents", parentIds);			//put ids of all parents to make them invisible in the list
						b.putInt("categoryid", temp.getId());
						i.putExtras(b);
						startActivity(i);
					}
					//Toast.makeText(AddMoreConnections.this, "Left to right", Toast.LENGTH_LONG).show();
				}
				return false;
			}
		});
	}
	public void addListenerToFinishButton(){
		commitButton = (Button) findViewById(R.id.addConnCommitButton);
		commitButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				int tempid;
				Iterator<Integer> iter = selectedHolders.keySet().iterator();
				LinkedHashMap<Integer, AbstractHolder> subholders = thiscat.getsubholders();
				/*
				 * First set new subholder list, then complete this activity
				 */
				while(iter.hasNext()){
					tempid = iter.next();
					
					/*
					 * Find the abstract holder
					 * Then clear its inCategory property
					 */
					AbstractHolder selectedHolder = SocialRssModel.Instance(null).allCategories().get(tempid);
					if(selectedHolder == null){
						selectedHolder = SocialRssModel.Instance(AddMoreConnections.this).getAbstractHolder(tempid, "", false);
					}
					
					/*
					 * Take necessary actions
					 */
					if(selectedHolders.get(tempid)){						//if holder is selected
						if(!subholders.containsKey(tempid)){				//if it was not selected before
							if(selectedHolder.isGroup()){
								ArrayList<Group> catArray = SocialRssModel.Instance(null).outerCategories();
								catArray.remove(selectedHolder);
							}
							selectedHolder.setParentId(thiscat.getId());
							selectedHolder.setTurnedOn(thiscat.isTurnedOn());
							SocialRssModel.Instance(null).updateConnection((FollowedPerson) selectedHolder, new String[]{ConnectionTable.SELECTED});
							/*
							 * Also insert the row into database
							 */
							SocialRssModel.Instance(null).addNewRowInTo_InGroupTable(thiscat.getId(), tempid);
						}
					}
					else{													//if not selected
						if(subholders.containsKey(tempid)){					//if it was selected before
							/*
							 * Also remove the related row from database
							 */
							SocialRssModel.Instance(null).deleteRow_InGroupTable(thiscat.getId(), tempid);
							selectedHolder.setParentId(-1);
							if(selectedHolder.isGroup()){
								SocialRssModel.Instance(null).outerCategories().add((Group)selectedHolder);
							}
							selectedHolder.setTurnedOn(false);
							SocialRssModel.Instance(null).updateConnection((FollowedPerson) selectedHolder, new String[]{ConnectionTable.SELECTED});
						}
					}
				}
				/*
				 * End of setting
				 */
				
				thiscat.setSubHolders(null);
				//Back to main activity
				Intent i = new Intent(AddMoreConnections.this, OuterCategoryViewController.class);
				i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(i);
				
			}
		});
	}
	public void addListenerToSelectConnTypeButton(){
		selectConnTypeButton = (Button) findViewById(R.id.selectConnTypeButton);
		socialNetworkSelectListener = new SelectTypeClickListener((Context)this,
				(LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE), conntype, R.id.searchEditText);
		selectConnTypeButton.setOnClickListener(socialNetworkSelectListener);
	}
	public void addListenerOnSearchConnTextView(){
		searchConnTextView = (TextView) findViewById(R.id.searchEditText);
		searchConnTextView.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				int listNotOnViewsize = listNotOnView.size();
				int connlistsize = connlist.size();
				
				for(int i= 0; i < connlistsize; i++){
					if(!connlist.get(i).connNameContains(s.toString())){
						listNotOnView.add(connlist.remove(i));
						i--;
						connlistsize--;
					}
				}
				for(int i=0; i < listNotOnViewsize; i++){
					if(listNotOnView.get(i).connNameContains(s.toString())){
						connlist.add(listNotOnView.remove(i));
						i--;
						listNotOnViewsize--;
					}
				}
				((CustomAdapter) listAdapter).updateList(connlist);
				listAdapter.notifyDataSetChanged();
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,	int after) {				
			}
			
			@Override
			public void afterTextChanged(Editable s) {				
			}
		});
	}
	private void configureConnListForAdapter(){
		// Create and populate a List of planet names.
		selectedHolders = new LinkedHashMap<Integer, Boolean>();
	    listNotOnView = new ArrayList<AbstractHolder>();
	    connlist = new ArrayList<AbstractHolder> (4);
	    
	    connlist.addAll(SocialRssModel.Instance(this).allConnections());
	  	this.addCategoriesIntoListView();
	    
	    
	}
	/**
	 * It put all outer categories into listview with
	 * subcategories which this category contains
	 * 
	 * It also checks holders which this category contains
	 */
	private void addCategoriesIntoListView(){
		ArrayList<AbstractHolder> tempList = new ArrayList<AbstractHolder>();
		tempList.addAll(SocialRssModel.Instance(this).outerCategories());
	    
	    
	    //now find holders which are in this group
	    Iterator<Integer> iter = thiscat.getsubholders().keySet().iterator();
	    int itemid;
	    AbstractHolder tempHolder;
	    while(iter.hasNext()){
	    	tempHolder = null;
	    	itemid = iter.next().intValue();
	    	if(itemid < 5000000){
		    	tempHolder = SocialRssModel.Instance(null).getAbstractHolder(itemid, "", true);		//look for whether it is a group or not
		    	if(tempHolder != null){								//if it is a Group object
		    		tempList.add(tempHolder);
		    	}
	    	}
	    	selectedHolders.put(itemid, true);
	    }
	    tempList.remove(thiscat);
	    for(int i=0; i<idsOfParents.length; i++)
	    	tempList.remove(SocialRssModel.Instance(null).allCategories().get(idsOfParents[i]));
	    connlist.addAll(tempList);
	    allHolders.put(SocialNetworkNames.CATEGORY, tempList);		//store related categories into hash map
	}
	public void adjustButtonListener_setConnList(){
		boolean allSocialNetworksAreSelected = true;
		for(int i=0; i<conntype.size(); i++){
			if(!conntype.get(i).getStatus())
				allSocialNetworksAreSelected = false;
		}
		if(allSocialNetworksAreSelected){		//if all of them are selected
			connlist.removeAll(connlist);
			connlist.addAll(SocialRssModel.Instance(null).allConnections());
		}
		else{									//if some of them are selected
			connlist.removeAll(connlist);
			for(int i=0; i<4;i++){
				StringWithStatus temp = conntype.get(i);
				if(temp.getStatus()){			//if this conntype is selected
					if(allHolders.containsKey(temp.getName())){				//if it is already in linked hash map, directly insert it from there
						connlist.addAll(allHolders.get(temp.getName()));
					}
					else{													//if it is not in linked hash map
						Iterator<AbstractHolder> iter = SocialRssModel.Instance(null).socialNetworksWithConnections().get(temp.getName()).values().iterator();
						ArrayList<AbstractHolder> tempList = new ArrayList<AbstractHolder>();		
						while(iter.hasNext()){								//take all connections in selected social network
							tempList.add(iter.next());
						}
						allHolders.put(temp.getName(), tempList);			//put them all into hash map with a key which is the name of social network
						connlist.addAll(tempList);							//also put them into connlist which are used by listview
					}
				}
			}
		}
		if(conntype.get(4).getStatus()){		//if category is also selected
			if(allHolders.containsKey(conntype.get(4).getName())){			//if category list has been already stored into hashmap
				connlist.addAll(allHolders.get(conntype.get(4).getName()));
			}
			else
				this.addCategoriesIntoListView();
		}
		((CustomAdapter) listAdapter).updateList(connlist);
		listAdapter.notifyDataSetChanged();
	}
	private class CustomAdapter extends ArrayAdapter<AbstractHolder> {
		 
		  private ArrayList<AbstractHolder>  connectionList;
		 
		  public CustomAdapter(Context context, int textViewResourceId, ArrayList<AbstractHolder>  connList) {
			  super(context, textViewResourceId, connList);
			  this.connectionList = connList;
		  }
		  public void updateList(ArrayList<AbstractHolder>  connList){
			  connectionList = connList;
		  }
		  private class ViewHolder {
			  TextView name;
			  TextView acctype;
			  CheckBox sel;
		  }
		  
		  
		  
		  @Override
		  public View getView(int position, View convertView, ViewGroup parent) {

			  ViewHolder holder = null;
		 
			  if (convertView == null) {
				  LayoutInflater vi = (LayoutInflater)(((Activity)this.getContext()).getSystemService(Context.LAYOUT_INFLATER_SERVICE));
				  convertView = vi.inflate(R.layout.connlist, null);
			 
				  holder = new ViewHolder();
				  holder.name = (TextView) convertView.findViewById(R.id.connname);
				  holder.acctype = (TextView) convertView.findViewById(R.id.conntype);
				  holder.sel = (CheckBox) convertView.findViewById(R.id.ingroupitemlistcheckbox);
				  convertView.setTag(holder);
			  } 
			  else {
				  holder = (ViewHolder) convertView.getTag();
			  }
		 
			  final AbstractHolder conn = connectionList.get(position);
			  holder.name.setText(conn.getName());
			  holder.acctype.setText(conn.getConntype().toString());
			  holder.sel.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
						//conn.setTurnedOn(arg1);
						selectedHolders.put(conn.getId(), arg1);
					}
			  	});
			  Boolean inGroup = AddMoreConnections.this.selectedHolders.get(conn.getId());
			  if(inGroup != null)
				  holder.sel.setChecked(inGroup.booleanValue());
			  else
				  holder.sel.setChecked(false);
			  holder.sel.setTag(conn);
			  return convertView;
		 
		  }
	}
}
